package com.plugin.manage.service.impl;

import com.plugin.core.model.entity.SysMenu;
import com.plugin.manage.mapper.SysMenuMapper;
import com.plugin.manage.mapper.SysPermissionMapper;
import com.plugin.manage.service.ISysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统菜单服务实现类
 * 
 * @author mark
 * @date 2025-07-28
 */
@Service
@Slf4j
public class SysMenuServiceImpl implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addMenu(SysMenu sysMenu) {
        if (!StringUtils.hasText(sysMenu.getMenuName())) {
            throw new RuntimeException("菜单名称不能为空");
        }

        if (!StringUtils.hasText(sysMenu.getTitle())) {
            throw new RuntimeException("菜单标题不能为空");
        }

        // 检查菜单名称是否已存在
        if (checkMenuNameExists(sysMenu.getMenuName(), sysMenu.getParentId(), null)) {
            throw new RuntimeException("菜单名称已存在");
        }

        // 设置默认值
        if (sysMenu.getParentId() == null) {
            sysMenu.setParentId(0L); // 默认顶级菜单
        }
        if (sysMenu.getOrderNum() == null) {
            sysMenu.setOrderNum(0);
        }
        if (sysMenu.getStatus() == null) {
            sysMenu.setStatus("0"); // 默认正常状态
        }
        if (sysMenu.getVisible() == null) {
            sysMenu.setVisible("0"); // 默认显示
        }

        int result = sysMenuMapper.insert(sysMenu);
        if (result > 0) {
            log.info("新增菜单成功，菜单ID：{}", sysMenu.getMenuId());
            return sysMenu.getMenuId();
        } else {
            throw new RuntimeException("新增菜单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMenu(Long menuId) {
        if (menuId == null) {
            throw new RuntimeException("菜单ID不能为空");
        }

        // 检查是否有子菜单
        List<SysMenu> children = getMenusByParentId(menuId);
        if (!children.isEmpty()) {
            throw new RuntimeException("存在子菜单，无法删除");
        }

        // 删除菜单相关的权限
        sysPermissionMapper.deleteByResourceId(menuId);

        // 删除菜单
        int result = sysMenuMapper.deleteById(menuId);
        if (result > 0) {
            log.info("删除菜单成功，菜单ID：{}", menuId);
            return true;
        } else {
            throw new RuntimeException("删除菜单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMenu(SysMenu sysMenu) {
        if (sysMenu.getMenuId() == null) {
            throw new RuntimeException("菜单ID不能为空");
        }

        if (StringUtils.hasText(sysMenu.getMenuName())) {
            // 检查菜单名称是否已存在（排除自己）
            if (checkMenuNameExists(sysMenu.getMenuName(), sysMenu.getParentId(), sysMenu.getMenuId())) {
                throw new RuntimeException("菜单名称已存在");
            }
        }

        int result = sysMenuMapper.updateById(sysMenu);
        if (result > 0) {
            log.info("更新菜单成功，菜单ID：{}", sysMenu.getMenuId());
            return true;
        } else {
            throw new RuntimeException("更新菜单失败");
        }
    }

    @Override
    public SysMenu getMenuById(Long menuId) {
        if (menuId == null) {
            throw new RuntimeException("菜单ID不能为空");
        }

        SysMenu menu = sysMenuMapper.selectByMenuId(menuId);
        if (menu == null) {
            throw new RuntimeException("菜单不存在");
        }

        return menu;
    }

    @Override
    public List<SysMenu> getMenuList(int offset, int limit, SysMenu sysMenu) {
        return sysMenuMapper.selectMenuList(offset, limit, sysMenu);
    }

    @Override
    public List<SysMenu> getAllMenus() {
        return sysMenuMapper.selectAllMenus();
    }

    @Override
    public Integer countMenus(SysMenu sysMenu) {
        return sysMenuMapper.countMenus(sysMenu);
    }

    @Override
    public boolean checkMenuNameExists(String menuName, Long parentId, Long menuId) {
        if (!StringUtils.hasText(menuName)) {
            return false;
        }
        if (parentId == null) {
            parentId = 0L;
        }
        return sysMenuMapper.checkMenuNameExists(menuName, parentId, menuId) > 0;
    }

    @Override
    public List<SysMenu> getMenusByParentId(Long parentId) {
        if (parentId == null) {
            parentId = 0L;
        }
        return sysMenuMapper.selectMenusByParentId(parentId);
    }

    @Override
    public List<SysMenu> buildMenuTree(Long parentId) {
        if (parentId == null) {
            parentId = 0L;
        }

        List<SysMenu> menus = sysMenuMapper.selectMenuTree(parentId);
        List<SysMenu> menuTree = new ArrayList<>();

        for (SysMenu menu : menus) {
            // 递归构建子菜单
            List<SysMenu> children = buildMenuTree(menu.getMenuId());
            // 这里可以设置children属性，如果SysMenu有children字段的话
            menuTree.add(menu);
        }

        return menuTree;
    }

    @Override
    public List<SysMenu> getMenusByUserId(Long userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return sysMenuMapper.selectMenusByUserId(userId);
    }

    @Override
    public List<SysMenu> getMenusByRoleId(Long roleId) {
        if (roleId == null) {
            throw new RuntimeException("角色ID不能为空");
        }
        return sysMenuMapper.selectMenusByRoleId(roleId);
    }

    @Override
    public List<SysMenu> getMenusBySystem(Integer system) {
        if (system == null) {
            throw new RuntimeException("系统类型不能为空");
        }
        return sysMenuMapper.selectMenusBySystem(system);
    }

    @Override
    public List<SysMenu> getMenusByType(String menuType) {
        if (!StringUtils.hasText(menuType)) {
            throw new RuntimeException("菜单类型不能为空");
        }
        return sysMenuMapper.selectMenusByType(menuType);
    }

    @Override
    public List<SysMenu> getActiveMenus() {
        return sysMenuMapper.selectActiveMenus();
    }

    @Override
    public SysMenu getMenuByPerms(String perms) {
        if (!StringUtils.hasText(perms)) {
            throw new RuntimeException("权限标识不能为空");
        }
        return sysMenuMapper.selectMenuByPerms(perms);
    }

    @Override
    public List<SysMenu> exportMenus(SysMenu queryMenu) {
        // 导出所有符合条件的菜单，不分页
        return sysMenuMapper.selectMenuList(0, Integer.MAX_VALUE, queryMenu);
    }

    @Override
    public List<SysMenu> getMenuSelectList() {
        // 只返回正常状态的菜单用于选择
        SysMenu queryMenu = new SysMenu();
        queryMenu.setStatus("0"); // 正常状态
        queryMenu.setVisible("0"); // 显示
        return sysMenuMapper.selectMenuList(0, Integer.MAX_VALUE, queryMenu);
    }
}
